<template>
  <el-card>
    <h2>本机充值</h2>
    <el-form :model="form" label-width="100px">

      <el-form-item label="充值金额">
        <el-input v-model="form.rechargeAmount" placeholder="请输入充值金额" type="number" />
      </el-form-item>
      <el-form-item label="支付方式">
        <el-select v-model="form.paymentId" placeholder="请选择支付方式">
          <el-option
              v-for="method in paymentMethods"
              :key="method.id"
              :label="method.payment_method_name"
              :value="method.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="submitRecharge">提交充值</el-button>
  </el-card>
</template>

<script>
import {ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";

export default {
  name: "Recharge",
  setup() {
    // 定义表单
    const form = ref({
      customerId: "", // 自动填充
      rechargeAmount: "",
      paymentId: null,
    });

    const paymentMethods = ref([]);

    // 获取支付方式
    const fetchPaymentMethods = async () => {
      try {
        const response = await axios.get("/payment/methods");
        paymentMethods.value = response.data;
      } catch (error) {
        ElMessage.error("获取支付方式失败");
      }
    };

    // 从 localStorage 获取客户 ID
    const initializeCustomerId = () => {
      const userData = localStorage.getItem("user");
      if (userData) {
        const user = JSON.parse(userData);
        form.value.customerId = user.id; // 从 user 对象中获取 id
      } else {
        ElMessage.error("未登录，请先登录");
      }
    };

    // 提交充值
    const submitRecharge = async () => {
      if (!form.value.customerId || !form.value.rechargeAmount || !form.value.paymentId) {
        ElMessage.warning("请填写完整信息");
        return;
      }

      try {
        const payload = {
          customerId: form.value.customerId,
          rechargeAmount: form.value.rechargeAmount,
          paymentId: form.value.paymentId,
        };
        const response = await axios.post("/recharge", payload);
        ElMessage.success(response.data);
      } catch (error) {
        ElMessage.error("充值失败: " + error.message);
      }
    };

    // 页面加载时初始化
    onMounted(() => {
      initializeCustomerId();
      fetchPaymentMethods();
    });

    return {
      form,
      paymentMethods,
      submitRecharge,
    };
  },
};
</script>

<style scoped>
</style>
